package im.elephas.androfan.service;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import im.elephas.androfan.activity.ReplyStatusActivity;
import im.elephas.androfan.activity.FriendsStatusActivity;
import im.elephas.androfan.fanfouapi.FanfouApi;
import im.elephas.androfan.fanfouapi.events.IErrorEvent;
import im.elephas.androfan.fanfouapi.events.IStatusesEvent;
import im.elephas.androfan.fanfouapi.items.StatusItem;
import im.elephas.androfan.util.ImageGetter;
import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class AndrofanService extends Service implements IErrorEvent {

	private FanfouApi mFanfouApi;
	private AndrofanService mAndrofanService = this;
	private Timer mTimer;
	private StatusItem lastReplyStatusItem;
	private int replyStatusCount;
	private StatusItem lastFriendsStatusItem;
	private int friendsStatusCount;
	private AndrofanBinder mBinder;

	private NotificationManager mNotificationManager;

	@Override
	public void onCreate() {
		mFanfouApi = FanfouApi.getInstance();
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mBinder = new AndrofanBinder();
		mTimer = new Timer();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onRebind(Intent intent) {
		// TODO Auto-generated method stub
		super.onRebind(intent);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		return super.onUnbind(intent);
	}

	public class AndrofanBinder extends Binder implements IAndrofanService {

		@Override
		public void startReplyTimelineCheck(int count) {
			startReplyCheck(count);
		}

		@Override
		public void startFriendsTimelineCheck(int count) {
			startFriendsCheck(count);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	private void preReplyCheck() {
		try {
			List<StatusItem> list = mFanfouApi.getReplyStatusesList();
			lastReplyStatusItem = list.get(0);
			replyStatusCount = list.size();
		} catch (Exception e) {
			lastReplyStatusItem = null;
			replyStatusCount = 0;
		}
	}

	private void preFriendsCheck() {
		try {
			List<StatusItem> list = mFanfouApi.getFriendsStatusesList();
			lastFriendsStatusItem = list.get(0);
			friendsStatusCount = list.size();
		} catch (Exception e) {
			lastFriendsStatusItem = null;
			friendsStatusCount = 0;
		}
	}

	public void startReplyCheck(int period) {
		preReplyCheck();
		TimerTask tt = new TimerTask() {

			@Override
			public void run() {
				mFanfouApi.getReplyTimeline(10, new IStatusesEvent() {

					@Override
					public void statusesHandler(List<StatusItem> lsi) {
						if (lsi.size() == 0) {
							preReplyCheck();
							return;
						}
						if (lastReplyStatusItem == null
								|| lsi.get(0).getId() != lastReplyStatusItem
										.getId()) {
							Notification notification = new Notification(
									R.drawable.ic_menu_info_details, mFanfouApi
											.getUser().getScreenName()
											+ " 你有新回复", System
											.currentTimeMillis());
							Intent intent = new Intent(mAndrofanService,
									ReplyStatusActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							PendingIntent pi = PendingIntent.getActivity(
									mAndrofanService, 0, intent, 0);
							notification.setLatestEventInfo(mAndrofanService,
									"你有" + (lsi.size() - replyStatusCount)
											+ "条新回复", lsi.get(0).getText(), pi);
							mNotificationManager.notify(0, notification);
						}
						preReplyCheck();
					}
				}, mAndrofanService, "refresh");
			}
		};
		mTimer.schedule(tt, 0, period);
	}

	public void startFriendsCheck(int period) {
		preFriendsCheck();
		TimerTask tt = new TimerTask() {

			@Override
			public void run() {
				mFanfouApi.getFriendsTimeline(10, new IStatusesEvent() {

					@Override
					public void statusesHandler(List<StatusItem> lsi) {
						if (lsi.size() == 0) {
							preFriendsCheck();
							return;
						}
						if (lastFriendsStatusItem == null
								|| lsi.get(0).getId() != lastFriendsStatusItem
										.getId()) {
							Notification notification = new Notification(
									R.drawable.ic_menu_info_details, mFanfouApi
											.getUser().getScreenName()
											+ " 你有新消息", System
											.currentTimeMillis());
							Intent intent = new Intent(mAndrofanService,
									FriendsStatusActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							PendingIntent pi = PendingIntent.getActivity(
									mAndrofanService, 0, new Intent(
											mAndrofanService,
											FriendsStatusActivity.class), 0);
							notification.setLatestEventInfo(mAndrofanService,
									"你有" + (lsi.size() - friendsStatusCount)
											+ "条新消息", lsi.get(0).getText(), pi);
							mNotificationManager.notify(1, notification);
						}
						preFriendsCheck();
					}
				}, mAndrofanService, "refresh");
			}
		};
		mTimer.schedule(tt, 0, period);
	}

	@Override
	public void errorHandler() {
		Toast toast = Toast.makeText(mAndrofanService, "网络出现问题，重启服务前不在检查更新",
				Toast.LENGTH_LONG);
		toast.show();
		mTimer.cancel();
	}

}
